package cn.bossfriday.im.api.processor.user;

import cn.bossfriday.common.register.HttpApiRoute;
import cn.bossfriday.common.router.ClusterRouterFactory;
import cn.bossfriday.common.rpc.actor.ActorRef;
import cn.bossfriday.im.api.actor.GetAccessAddressAckActor;
import cn.bossfriday.im.common.api.ApiResponseHelper;
import cn.bossfriday.im.common.api.BaseHttpProcessor;
import cn.bossfriday.im.common.codec.ImTokenCodec;
import cn.bossfriday.im.common.entity.ImToken;
import cn.bossfriday.im.common.entity.result.ResultCode;
import cn.bossfriday.im.common.message.api.user.NavigateRequest;
import cn.bossfriday.im.common.message.api.user.NavigateResponse;
import cn.bossfriday.im.common.message.rpc.access.GetAccessAddressInput;
import cn.bossfriday.im.common.rpc.message.ApiMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;

import static cn.bossfriday.im.common.constant.ApiConstant.API_ROUTE_KEY_USER_NAVI;
import static cn.bossfriday.im.common.constant.ImConstant.ACTOR_ACCESS_GET_ACCESS_ADDRESS;

/**
 * NavigateProcessor
 *
 * @author chenx
 */
@Slf4j
@HttpApiRoute(apiRouteKey = API_ROUTE_KEY_USER_NAVI)
public class NavigateProcessor extends BaseHttpProcessor {

    @Override
    protected void doRequest(ChannelHandlerContext ctx, FullHttpRequest httpRequest, String apiVersion, long appId) {
        try {
            NavigateRequest request = this.getRequestPayload(httpRequest, NavigateRequest.class);
            ImToken imToken = ImTokenCodec.decode(request.getToken());
            if (imToken.getAppId() != appId) {
                ApiResponseHelper.sendApiResponse(ctx, ResultCode.API_INVALID_APP_KEY);
                return;
            }

            String userId = imToken.getUserId();
            ApiMessage apiMessage = this.getApiMessage(apiVersion,
                    appId,
                    ACTOR_ACCESS_GET_ACCESS_ADDRESS,
                    userId,
                    userId,
                    GetAccessAddressInput.builder().build());

            NavigateResponse response = NavigateResponse.builder()
                    .appId(imToken.getAppId())
                    .userId(userId)
                    .deviceId(imToken.getDeviceId())
                    .build();
            ActorRef sender = ClusterRouterFactory.getClusterRouter().getActorSystem().actorOf(API_RPC_TTL, GetAccessAddressAckActor.class, ctx, response);
            this.routeMessage(apiMessage, sender);
        } catch (Exception ex) {
            log.error("HttpProcessor.doRequest() error!", ex);
            ApiResponseHelper.sendApiResponse(ctx, ResultCode.SYSTEM_ERROR);
        }
    }
}
